module(...,package.seeall)
local nodeapi=require'zdc.nodeapi'
require'zdc.act'

local _cmdact = {
clock=os.clock,collectgarbage=collectgarbage,pairs=pairs,ipairs=ipairs,string=string,
table=table,bit=bit,assert=assert,math=math,type=type
}
local _cmdact_mt = {__metatable = {},__index = _cmdact}

---id,data,repository
function new(env)
   local node = setmetatable({env=env},_cmdact_mt)
   node.api=node 
   node.print=function (...) env:_print(...) end
   node.put=function (...) env:_put(...) end
   node.dal=env.dal
   return node
end

function _cmdact:create(pa,sub,mc,dft)
	local env=self.env
	return nodeapi.createsub(env.user,env.dal,env.dal:GetNode(pa),sub,mc,dft)
end
function _cmdact:makenode(id,data,ik,st)
	local env=self.env
	return nodeapi.makenode(env.user,env.dal,id,data,ik,st)
end
function _cmdact:removenode(id,deep)
	local env=self.env
	return nodeapi.removenode(env.user,env.dal,id,deep)
end
function _cmdact:clone(from,toid,opt,update)
	local env=self.env
	local a,b= nodeapi.clone(env.user,env.dal,env.dal:GetNode(from),toid,opt)
	if not a or not update then return a,b end
	local pa,sub=zdc.idutil.GetParent(toid)
	return nodeapi.updatesub(env.user,env.dal,env.dal:GetNode(pa),sub,update)
end
function _cmdact:replace(pa,sub,mc,dft)
	local env=self.env
	return nodeapi.replacesub(env.user,env.dal,env.dal:GetNode(pa),sub,mc,dft)
end
function _cmdact:mset(pa,sub,mc,dft)
	local env=self.env
	return nodeapi.updatesub(env.user,env.dal,env.dal:GetNode(pa),sub,mc,dft)
end
function _cmdact:delete(pa,sub)
	local env=self.env
	local pan=env.dal:GetNode(pa)
	if not pan then return nil,'not find node '..pa end
	return nodeapi.delsub(env.user,env.dal,pan,sub)
end
function _cmdact:set(pa,fd,val)
	local env=self.env
	return nodeapi.set(env.user,env.dal,env.dal:GetNode(pa),fd,val)
end
function _cmdact:unset(pa,...)
	local env=self.env
	local r,e
	local arg={...}
	local n=env.dal:GetNode(pa)
	for i=1,#arg do
		r,e=nodeapi.unset(env.user,env.dal,n,arg[i])
		if not r then
			return r,e
		else
		    --env:_put('OK\n')
		end
	end
	return true	
end
function _cmdact:get(pa,...)
	local env=self.env
	local r,e
	local arg={...}
	local n=env.dal:GetNode(pa)
	local rs={}
	for i=1,#arg do
		r,e=nodeapi.get(env.user,env.dal,n,arg[i])
		if not r then
			return r,e
		else
			rs[arg[i]]=r;
		    --env:_put('OK\n')
		end
	end
	return rs
end
function _cmdact:commit()
	return self.env:commit()
end

function _cmdact:dropdb()
	local env=self.env
	env._cfghaserror=false
	env.dal:DropAll("cmd dropdb")
	return true
end

function _cmdact:abort()
	local env=self.env
	env._cfghaserror=false
	env.dal:Abort()
	return true
end
function _cmdact:GetEx(nid,args,deep)
	local dal=self.env.dal
	local n=dal:GetNode(nid)
	if not n then return false end
	return zdc.act.actions.Get(self.env.user,dal,n,'zGet',args,deep)
end
